# Create your views here.
import os
from datetime import datetime

from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from django.db.models import Q, OuterRef, Subquery
from django.http import JsonResponse
from django.views import View

from article.models import Article, SysArticleSerializer
from articleType.models import ArticleType
from sunshinelife_V2 import settings


class AddArticleView(View):
    def post(self, request):  # 添加文章
        id = request.POST.get("id", None)
        title = request.POST.get("title")
        content = request.POST.get("content")
        type_id = request.POST.get("type_id")
        is_active = request.POST.get("is_active", "false").strip().lower() == "true"
        author = request.POST.get("author")
        if id is None or id == "-1" or id == "":  # 当id为空值时，新增文章
            try:
                article = Article.objects.create(
                    title=title,
                    content=content,
                    type_id=type_id,
                    is_active=bool(is_active),
                    author=author,
                    update_time=datetime.now().date(),
                )
                query = Q()
                if title:
                    query &= Q(title__icontains=None)
                if type_id:
                    query &= Q(type_id=None)
                type_name_subquery = ArticleType.objects.filter(
                    id=OuterRef('type_id')  # 关联 article 的 type_id
                ).values('type_name')[:1]  # 取第一个匹配结果的 type_name
                articles = Article.objects.annotate(
                    type_name=Subquery(type_name_subquery)).order_by('-update_time')
                return JsonResponse(
                    {"code": 200, "info": "添加成功！", "articleList": SysArticleSerializer(articles, many=True).data})
            except Exception as e:
                return JsonResponse({"code": 500, "msg": "添加失败", "error": str(e)})
        else:  # 修改文章
            try:
                article = Article.objects.get(id=id)
                article.title = title
                article.content = content
                article.type_id = type_id
                article.update_time = datetime.now().date()
                article.is_active = is_active
                article.save()
                query = Q()
                # 根据非空参数动态添加查询条件
                if id:
                    query &= Q(id=id)
                if title:
                    query &= Q(title__icontains=title)
                if type_id:
                    query &= Q(type_id=type_id)
                type_name_subquery = ArticleType.objects.filter(
                    id=OuterRef('type_id')  # 关联 article 的 type_id
                ).values('type_name')[:1]
                # 查询所有公告数据
                articles = Article.objects.annotate(
                    type_name=Subquery(type_name_subquery)).order_by('-update_time')
                return JsonResponse(
                    {"code": 200, "info": "修改成功！", "articleList": SysArticleSerializer(articles, many=True).data})
            except Exception as a:
                return JsonResponse({"code": 500, "info": "修改失败！"})


class SelectArticeView(View):
    def post(self, request):  # 查询文章
        id = request.POST.get("id", None)
        title = request.POST.get("title", None)
        is_active = request.POST.get("is_active", "false").strip().lower() == "true"
        type_id = request.POST.get("type_id", None)
        try:
            if id == '-1':  # 查询所有文章
                query = Q()
                if title:
                    query &= Q(title__icontains=title)
                if type_id:
                    query &= Q(type_id=type_id)
                type_name_subquery = ArticleType.objects.filter(
                    id=OuterRef('type_id')  # 关联 article 的 type_id
                ).values('type_name')[:1]  # 取第一个匹配结果的 type_name
                article = Article.objects.annotate(
                    type_name=Subquery(type_name_subquery)).order_by('-update_time')
                return JsonResponse(
                    {"code": 200, "info": "查询成功！", "articleList": SysArticleSerializer(article, many=True).data})
            else:
                # 初始化 Q 对象
                query = Q()
                # 根据非空参数动态添加查询条件
                if id:
                    query &= Q(id=id)
                if title:
                    query &= Q(title__icontains=title)
                if is_active is not None:  # 确保 is_active 不为 None
                    query &= Q(is_active=is_active)
                if type_id:
                    query &= Q(type_id=type_id)
            type_name_subquery = ArticleType.objects.filter(
                id=OuterRef('type_id')  # 关联 article 的 type_id
            ).values('type_name')[:1]  # 取第一个匹配结果的 type_name

            # 主查询添加注释字段
            articles = Article.objects.filter(query).annotate(
                type_name=Subquery(type_name_subquery)).order_by('-update_time')

            article_lists = SysArticleSerializer(articles, many=True).data

            return JsonResponse(
                {"code": 200, "info": "查询成功！", "articleList": article_lists})
        except Exception as e:
            return JsonResponse({"code": 500, "info": "查询失败！", "error": str(e)})


class UploadImageView(View):
    def post(self, request):
        image_file = request.FILES.get("image")
        try:
            if not image_file:
                return JsonResponse({"code": 400, "msg": "图片文件不能为空"})

            # 定义图片存储路径
            img_dir = os.path.join('img')
            if not os.path.exists(img_dir):
                os.makedirs(img_dir)

            # 生成时间戳文件名
            timestamp = datetime.now().strftime("%Y%m%d%H%M%S")  # 格式：年月日时分秒
            file_extension = os.path.splitext(image_file.name)[1]  # 获取文件扩展名（如 .jpg）
            new_file_name = f"{timestamp}{file_extension}"  # 新文件名：时间戳 + 扩展名

            # 保存图片文件
            file_name = default_storage.save(os.path.join(img_dir, new_file_name), ContentFile(image_file.read()))
            file_url = os.path.join(settings.MEDIA_URL, 'img', new_file_name)

            # 生成完整链接
            full_file_url = request.build_absolute_uri(file_url)

            return JsonResponse({"code": 200, "msg": "图片上传成功", "img_url": full_file_url})
        except Exception as e:
            return JsonResponse({"code": 500, "msg": "图片上传失败", "error": str(e)})
